<template>
  <div>
    <Card>
      <template #title>查询数据</template>
      <template #content>
        <TabView>
          <TabPanel header="Mysql">
            <div class="flex gap-4">
              <div class="p-inputgroup flex-1">
                <span class="p-inputgroup-addon">数据库</span>
                <Dropdown
                  v-model="selectedKey.database"
                  :options="toolStore.getDbs"
                  filter
                  optionLabel="name"
                  class="w-full md:w-14rem"
                >
                </Dropdown>
              </div>
              <div class="p-inputgroup flex-1">
                <span class="p-inputgroup-addon">数据表</span>
                <Dropdown
                  v-model="selectedKey.table"
                  :options="toolStore.getTables"
                  filter
                  optionLabel="name"
                  class="w-full md:w-14rem"
                >
                  <template #value="slotProps">
                    <div v-if="slotProps.value" class="flex align-items-center">
                      <span>{{ slotProps.value.name }}</span>
                    </div>
                    <span v-else>
                      {{ slotProps.placeholder }}
                    </span>
                  </template>
                  <template #option="slotProps">
                    <div class="flex align-items-center">
                      <span>{{ slotProps.option.code }}</span>
                      <span class="text-sm text-500">{{ slotProps.option.name }}</span>
                    </div>
                  </template>
                </Dropdown>
              </div>
            </div>
            <Textarea v-model="sql" rows="3" class="w-full mt-2 mb-2" />
          </TabPanel>
        </TabView>
        <div class="flex flex-column">
          <div>
            <Button
              label="SELECT *"
              severity="info"
              text
              @click="
                sql = `SELECT * FROM \`${selectedKey.table.code}\` ORDER BY 1 DESC;`
              "
            />
            <Button
              label="SHOW CREATE TABLE"
              severity="info"
              text
              @click="sql = `SHOW CREATE TABLE \`${selectedKey.table.code}\`;`"
            />
            <Button label="清除" severity="info" text @click="sql = ''" />
          </div>
          <Button label="查询" @click="handleSubmit" class="mt-3" />
        </div>
      </template>
    </Card>
    <Card class="mt-3">
      <template #title>查询结果</template>
      <template #content>
        <div v-if="toolStore.isTableData">
          <DataTable :value="toolStore.sqlData" tableStyle="min-width: 50rem">
            <Column v-for="col of toolStore.colInfoList" :key="col.columnName" :field="col.columnName" :header="col.columnComment"></Column>
          </DataTable>
        </div>
        <div v-else>
          <h3>{{ toolStore.sqlData[0]?.Table }}</h3>
          <!-- <code v-html="highlightedCode"></code> -->
          <pre id="preRef"><code>{{ toolStore.getSql }}</code></pre>
        </div>
      </template>
    </Card>
  </div>
</template>

<script setup lang="ts">
import {
  Card,
  TabPanel,
  TabView,
  Textarea,
  Button,
  Dropdown,
  DataTable,
  Column
} from "@/utils/primevue";
import { ref, onMounted, watch, toRef } from "vue";
import useToolStore from "@/stores/tool";
import type { TDatabase, TTableItem } from "@/typing/tool";
import hljs from 'highlight.js/lib/core';
import lang from 'highlight.js/lib/languages/sql';
import 'highlight.js/styles/atom-one-dark.min.css'


const toolStore = useToolStore();
const sql = ref("");
const selectedKey = ref({ database: { name: '', code: ''}, table: { name: '', code: '' } });
const preRef = ref(null)
let highlightedCode = ''

hljs.registerLanguage('sql', lang);

watch([() => toolStore.getDbs, () => toolStore.getTables], (newVal) => {
  console.log("newVal", newVal);
  selectedKey.value.database = newVal[0][0];
  selectedKey.value.table = newVal[1][0];
});

watch(() => toolStore.getSql, (newVal) => {
  // console.log('newVal', newVal)
  // highlightedCode = hljs.highlight(
  //   newVal,
  //   { language: 'sql', }
  // ).value
  if (preRef.value) {
    hljs.highlightElement(preRef.value);
  }
});

onMounted(async () => {

  toolStore.queryDbs((database: TDatabase) => {
    toolStore.queryTableName({ dbName: database.dbName });
  });
});

const handleSubmit = () => {

  toolStore.executeSql(
    { dbName: selectedKey.value.database.code, tableName: selectedKey.value.table.code, sql: sql.value },
    // 是否是查看表数据（true表数据，false表结构）
    !!sql.value.toLocaleLowerCase().trim().startsWith('select')
  )
};
</script>

<style scoped lang="less">

</style>
